package com.ivyft.hive.hadoop;

import com.ivyft.hive.serde2.protobuf.IntLengthHeaderFile;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <pre>
 *
 * Created by IntelliJ IDEA.
 * User: zhenqin
 * Date: 15/4/8
 * Time: 14:44
 * To change this template use File | Settings | File Templates.
 *
 * </pre>
 *
 * @author zhenqin
 */
public class IntLengthHeaderRecordReader extends RecordReader<LongWritable, BytesWritable> {
    protected IntLengthHeaderFile.Reader in;

    protected final AtomicLong key = new AtomicLong(0);


    @Override
    public void initialize(InputSplit split,
                           TaskAttemptContext context
    ) throws IOException, InterruptedException {
        FileSplit fileSplit = (FileSplit) split;
        Configuration conf = context.getConfiguration();
        Path path = fileSplit.getPath();
        FileSystem fs = path.getFileSystem(conf);

        this.in = new IntLengthHeaderFile.Reader(conf, fs, path);
    }

    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {
        return in.hasNext();
    }

    @Override
    public LongWritable getCurrentKey() {
        return new LongWritable(key.addAndGet(1));
    }

    @Override
    public BytesWritable getCurrentValue() {
        return in.next();
    }

    /**
     * Return the progress within the input split
     * @return 0.0 to 1.0 of the input byte range
     */
    @Override
    public float getProgress() throws IOException {
        return 0.0f;
    }


    @Override
    public synchronized void close() throws IOException {
        in.close();
    }

}
